namespace NHibernate.Br.Exemplos.Core.Repository
{
    using System;
    using System.Collections;

    public abstract class BaseNHRepository<T>: IRepository<T>
    {
        private readonly ISession session;

        protected BaseNHRepository(ISession session)
        {
            this.session = session;
        }

        public T Add(T entity)
        {
            session.Save(entity);

            return entity;
        }

        public T Update(T entity)
        {
            session.Update(entity);

            return entity;
        }

        public void Remove(T entity)
        {
            session.Delete(entity);
        }

        public T Fetch(int id)
        {
            return session.Get<T>(id);
        }

        public T[] FetchAll()
        {
            ICriteria criteria = session.CreateCriteria(typeof(T));

            IList result = criteria.List();

            Array array = Array.CreateInstance(typeof(T), result.Count);

            result.CopyTo(array, 0);

            return (T[])array;
        }
    }
}